package org.renhj.rpc;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import org.renhj.common.RpcRequest;
import org.renhj.common.RpcResponse;

import java.util.List;

public class RpcDecoder extends ByteToMessageDecoder {
    private final Serializer serializer = new JSONSerializer();

    private final Class<?> clazz;

    public RpcDecoder(){
        this.clazz = RpcResponse.class;
    }

    public RpcDecoder(Class<?> clazz) {
        this.clazz = clazz;
    }


    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf byteBuf, List<Object> list) throws Exception {
        byteBuf.markReaderIndex();
        int  length = byteBuf.readInt();
        if (length < 0) {
            ctx.close();
        }
        if (byteBuf.readableBytes() < length) {
            byteBuf.resetReaderIndex();
            return;
        }
        byte[] bytes = new byte[length];
        byteBuf.readBytes(bytes);
        Object o = serializer.deserialize(clazz, bytes);
        list.add(o);
    }
}
